<?php

namespace App\Http\Controllers;

use App\Common\Exception\ErrorException;
use Illuminate\Support\Facades\Auth;
use App\Models\Backend\System\User;
use App\Models\Backend\System\Group;
use Illuminate\Support\Facades\Log;

class AppController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth');
    }

    /**
     * 主页
     */
    public function index()
    {
        $user = Auth::user();
        return view('databoard.index');
    }

    public function logout()
    {
        $url = request('url', env('APP_URL').route('homes',null,false));
        Auth::logout();
        return redirect($url);
    }

    public function download()
    {
        $realurl = explode('uploads',request()->get('url'))[1] ?? '';
        if ($realurl == ''){
            throw new ErrorException('文件路径不正确');
        }
        $url = public_path('uploads').$realurl;
        $real_name = request()->get('filename');
        $ext = strtolower(pathinfo($real_name,PATHINFO_EXTENSION ));
        if (in_array($ext,['jpg','png','jpeg','gif'])){
            $content_type = "image/*";
        }elseif (in_array($ext,['doc','docx','ppt','pptx','xls','xlsx'])){
            $content_type = "application/msword";
        }elseif ($ext == 'pdf'){
            $content_type = "application/pdf";
        }elseif($ext == 'txt'){
            $content_type = "text/plain";
        }elseif($ext == 'zip' || $ext == 'rar'){
            $content_type = "";
        }else{
            throw new ErrorException('格式不正确');
        }

        $headers=[
            "Content-Disposition"=>"attachment; filename=".$real_name,
            "Content-Transfer-Encoding"=>" binary",
            "Content-Type"=> $content_type
        ];

        return response()->download($url,$real_name,$headers);

    }

    public function downloadzip()
    {
        $real_name = request()->get('filename');
        $url = public_path('uploads/download/').$real_name;
        $ext = strtolower(pathinfo($real_name,PATHINFO_EXTENSION ));
        if (strtolower($ext) == 'zip'){
            $content_type = "application/x-zip-compressed";
        }else{
            throw new ErrorException('格式不正确');
        }

        $headers=[
            "Content-Disposition"=>"attachment; filename=".$real_name,
            "Content-Transfer-Encoding"=>" binary",
            "Content-Type"=> $content_type
        ];
        if (!file_exists($url)){
            throw new ErrorException('文件生成失败!');
        }

        return response()->download($url,$real_name,$headers)->deleteFileAfterSend();

    }
}
